export default (app) => {
  app.directive('debounce', {
    mounted (el, binding) {
      //  v-debounce="{click:handleMenu,args:[index]}"
      // v-debounce="[{click:change,delay:300},{click:change2,delay:300}]
      const { click, delay = 1000, args } = binding.value
      let time
      // 可能一个按钮会有多个事件
      const handleClick = () => {
        if (Array.isArray(click)) {
          click.forEach(element => {
            if (args && args.length > 0) {
              element(...args)
            } else {
              element()
            }
          })
        } else {
          if (args && args.length > 0) {
            click(...args)
          } else {
            click()
          }
        }
      }
      el.addEventListener('click', () => {
        const firstClick = !time
        // 确保第一次点击时会触发
        if (firstClick) {
          handleClick()
        }
        if (time) {
          clearTimeout(time)
        }
        time = setTimeout(() => {
          time = null
          if (!firstClick) {
            handleClick()
          }
        }, delay)
      })
    }
  })
}
